package com.itheima.rpc.client.cluster.loadbalance;

import com.itheima.rpc.annotation.HrpcLoadBalance;
import com.itheima.rpc.client.cluster.LoadBalanceStrategy;
import com.itheima.rpc.provider.ServiceProvider;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@HrpcLoadBalance(strategy = "polling")
public class PollingLoadBalanceStrategy implements LoadBalanceStrategy {

    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public ServiceProvider select(List<ServiceProvider> serviceProviders) {
        int index = 0;
        for (;;) {
            int old = count.get();
            index = old % serviceProviders.size();
            boolean success = count.compareAndSet(old, old + 1);
            if (success) {
                break;
            }
        }
        return serviceProviders.get(index);
    }
}
